﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.IO;

namespace myCommon.Config
{
    public class INIClass
    {
        public string inipath;
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        /// <summary> 
        /// 构造方法 
        /// </summary> 
        /// <param name="INIPath">文件路径</param> 
        public INIClass(string INIPath)
        {
            inipath = INIPath;
        }
        /// <summary> 
        /// 写入INI文件 
        /// </summary> 
        /// <param name="Section">项目名称(如 [TypeName] )</param> 
        /// <param name="Key">键</param> 
        /// <param name="Value">值</param> 
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.inipath);
        }

        /// <summary>(子功能)查询某个值是否存在于指定的INI文件的Section段。
        /// 这个Section的结构如下：
        /// [Section]
        /// Total=4
        /// 1=xxx
        /// 2=xxxx
        /// 3=xxxxx
        /// 4=xxxxxx
        /// 如果找到，则返回前面的序号，如果找不到，则返回-1
        /// </summary>
        public int CheckExistInINI(string Section, string KeyName, string strIn)
        {
            //INIClass myINIClass = new INIClass(INIPath);
            string sTemp;
            string Str;
            int Total;
            int i;
            Str = strIn.TrimEnd().TrimStart();//.ToUpper();
            Total = IniReadValue(Section, KeyName, 0);

            for (i = 0; i < Total; i++)
            {
                sTemp = IniReadValue(Section, (i).ToString(), "").Trim();
                if (sTemp.ToUpper ()  == Str.ToUpper ()) return i ;

            }
            return -1; 

        }
        /// <summary> 
        /// 读出INI文件 
        /// </summary> 
        /// <param name="Section">项目名称(如 [TypeName] )</param> 
        /// <param name="Key">键</param> 
        public string IniReadValue(string Section, string Key,string Default)
        {
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(Section, Key, Default, temp, 500, this.inipath);
            return temp.ToString();
        }
        /// <summary>读取整数
        /// 如果没有，或者读到的数据不可转为数字，返回DefaultValue
        /// </summary>
        public int IniReadValue(string Section, string Key, int DefaultValue)
        {
            string sTemp;
            int i;
            sTemp = IniReadValue(Section, Key,DefaultValue .ToString ()).Trim ();
            if (sTemp == "") return DefaultValue;
            else
            {
                try { i = Convert.ToInt32(sTemp); return i; }
                catch (FormatException) { return DefaultValue; }
            }
        }
        /// <summary>读取bool数，可识别的是"true","false","1","0",不区分大小写
        /// 如果没有，或者读到的数据不可转为布尔值，返回DefaultValue
        /// </summary>
        public bool IniReadValue(string Section, string Key, bool DefaultValue)
        {
            string sTemp;
            bool  i;
            sTemp = IniReadValue(Section, Key, DefaultValue.ToString()).Trim();
            if (sTemp == "") return DefaultValue;
            else
            {
                switch (sTemp)
                {
                    case "0": return false;
                    case "1": return true;
                    default:
                        {
                            try { i = Convert.ToBoolean(sTemp); return i; }
                            catch (FormatException) { return DefaultValue; }
                        }
                }
            }
        }
        /// <summary>读取双精度浮点数
        /// 如果没有，或者读到的数据不可转为数字，返回DefaultValue
        /// </summary>
        public double IniReadValue(string Section, string Key, double DefaultValue)
        {
            string sTemp;
            double i;
            sTemp = IniReadValue(Section, Key,DefaultValue .ToString ()).Trim ();
            if (sTemp == "") return DefaultValue;
            else
            {
                try { i = Convert.ToDouble (sTemp); return i; }
                catch (FormatException) { return DefaultValue; }
            }
        }
        /// <summary> 
        /// 验证文件是否存在 
        /// </summary> 
        /// <returns>布尔值</returns> 
        public bool ExistINIFile()
        {
            return File.Exists(inipath);
        }

        //---------------------20151010 add new functions by JM.Liu------------
        /// <summary>
        /// 查找"General"区的"ItemsCount"键的值，如果不存在则返回-1
        /// </summary>
        /// <returns></returns>
        public int Item_GetQty()
        {
            return this.IniReadValue("General", "ItemsCount", -1);   
        }

        /// <summary>
        /// 添加一个Item
        /// </summary>
        /// <param name="N_V">new string[,] { { "IP", "192.168.1.1" }, { "Description", "sdfasdf" } </param>
        public void Item_Add(string [,] N_V)
        {
            int ItemsCount=Item_GetQty ();
            if (ItemsCount < 1)//第一条
            {
                IniWriteValue("General", "ItemsCount", "1");

                for (int i = 0; i < N_V.Length / N_V.Rank; i++)
                {
                    IniWriteValue("Item0", N_V[i, 0], N_V[i, 1]);
                }
                
                
            }
            else //增加一条
            {
                IniWriteValue("General", "ItemsCount", (ItemsCount+1).ToString ());

                for (int i = 0; i < N_V.Length / N_V.Rank; i++)
                {
                    IniWriteValue("Item"+ ItemsCount.ToString ()  , N_V[i, 0], N_V[i, 1]);
                }
            }
           

            
        }
    }
    public class INIItems
    {
        public List<string[,]> Items = new List<string[,]>();
        public INIClass iniclass;
        public int ItemColumnsCount;
        public string[] ItemColumns;
        public int ItemCount;

        public INIItems (INIClass classItemSetting)
        {
            iniclass = classItemSetting ;
            ItemColumnsCount = GetItemColumns();
        }

        /// <summary>获取所有栏，存在ItemColumns[]里，并返回栏数量 </summary>
        /// <returns></returns>
        private int GetItemColumns()
        {

            ItemColumnsCount=iniclass.IniReadValue("General", "ItemColumnsCount", -1);
            ItemColumns = new string[ItemColumnsCount];
            for (int i = 0; i < ItemColumnsCount; i++)
            {
                ItemColumns[i] = iniclass.IniReadValue("General", "ItemColumn" + i.ToString(), "ERROR888");
            }
            return ItemColumnsCount;
        }

        /// <summary>设定Item一共有多少栏，每一栏的内容是什么
        /// </summary>
        /// <param name="columnName"></param>
        public void SetItemColumns(string [] columnName)
        {
            iniclass.IniWriteValue("General", "ItemColumnsCount", columnName.Length.ToString ());
            ItemColumnsCount = columnName.Length;
            for (int i = 0; i < columnName.Length; i++)
            {
                iniclass.IniWriteValue("General", "ItemColumn" + i.ToString(), columnName[i]);
            }

        }

        public void GetItemsFromINI()
        {
            ItemCount = iniclass.Item_GetQty();
            ItemColumnsCount = GetItemColumns();
            Items.Clear();
            string[,] item = new string[ItemColumnsCount, 2];

            for (int i = 0; i < ItemCount; i++)
            {
                item = new string[ItemColumnsCount, 2];
                for (int j = 0; j < ItemColumnsCount; j++)
                {
                    
                    item[j, 0] = ItemColumns[j];
                    item[j,1]= iniclass.IniReadValue("Item" + i.ToString(), ItemColumns[j], "NOFOUND");
                }
                Items.Add(item);
            }
        }


        public int AddItem(string[] subItems)
        {
            if (subItems.Length != ItemColumns.Length) return -1;
            string[,] item = new string[ItemColumns.Length, 2];
            for (int j = 0; j < ItemColumns.Length; j++)
            {

                item[j, 0] = ItemColumns[j];
                item[j, 1] = subItems [j];
            }
            Items.Add(item);
            return 1;
        }


        public void SaveItems()
        {
            iniclass.IniWriteValue("General", "ItemColumnsCount", ItemColumnsCount.ToString());
            for (int i = 0; i < ItemColumns.Length; i++)
            {
                iniclass.IniWriteValue("General", "ItemColumn" + i.ToString(), ItemColumns[i]);
            }

            iniclass.IniWriteValue("General", "ItemsCount", Items.Count.ToString());
            for (int i = 0; i < Items.Count; i++)
            {
                for(int j=0;j<ItemColumns .Length ;j++)
                iniclass.IniWriteValue("Item" + i.ToString(), Items[i][j, 0], Items[i][j, 1]);
            }
        }

        public void RemoveItem(int i)
        {
            Items.RemoveRange(i, 1);
            ItemCount--;
        }

        public void UpdateItem(int idx, string[] content)
        {
            RemoveItem(idx);
            string[,] item = new string[ItemColumns.Length, 2];

            for (int j = 0; j < ItemColumns.Length; j++)
            {

                item[j, 0] = ItemColumns[j];
                item[j, 1] = content[j];
            }
            Items.Insert (idx,item);
        }
    }
}
